package distriKub;

import java.io.*;
import java.net.*;

public class GameComClient {

	// Declaration section
	// clientClient: the client socket
	// os: the output stream
	// is: the input stream

	static Socket clientSocket = null;
	static PrintStream os = null;
	static BufferedReader is = null;
	static BufferedReader inputLine = null;
	static boolean closed = false;
	String responseLine;
	boolean allOK;


	public boolean sendGameMessage(String theMessage, InetAddress theAddress, int thePort, int timeToWait) {
		
		allOK = false;
		
		// Initialization section:
		// Try to open a socket on a given host and port
		// Try to open input and output streams
		try {
			clientSocket = new Socket(theAddress, thePort);
			clientSocket.setSoTimeout(timeToWait);
			os = new PrintStream(clientSocket.getOutputStream());
			is = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
		} catch (IOException IOEX) {
			System.out.println("\n===> GameComClient.java ===> Error Creating new Socket\n");
			IOEX.printStackTrace();
			allOK = false;
		}

		if (clientSocket != null && os != null && is != null) {
			os.println(theMessage);
		}
		
		try{ 
		    if ((responseLine = is.readLine()) != null) {
			System.out.println("===> GameComClient.java ===> Recieved back : " + responseLine);
		    }
		    if (responseLine.indexOf(ComRules.comTerminationString) != -1) closed = true;
		} catch (IOException e) {
		    System.err.println("IOException:  " + e);
		    allOK = false;
		}
		
		if (Integer.parseInt(responseLine) == theMessage.hashCode())
			allOK = true;

		return allOK;
		
		// End of sendGameMessage method
	}
	
	public void closeGameClient(){
		// Clean up:
		// close the output stream
		// close the input stream
		// close the socket
		
		if (os!=null) os.close();
		try{
		if (is!=null) is.close();
		if (clientSocket!=null) clientSocket.close();
		} catch (Exception EX){
			System.out.println("\n===> GameComClient.java ===> Error closing connection \n");
			EX.printStackTrace();
		}
	}
}